package com.jzy.chatglmsdk18753goldn.executor.aigc.qwen;

import com.alibaba.fastjson.JSON;
import com.jzy.chatglmsdk18753goldn.IOpenAiApi;
import com.jzy.chatglmsdk18753goldn.executor.Executor;
import com.jzy.chatglmsdk18753goldn.executor.result.ResultHandler;
import com.jzy.chatglmsdk18753goldn.model.*;
import com.jzy.chatglmsdk18753goldn.session.Configuration;
import okhttp3.*;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import org.jetbrains.annotations.Nullable;

import java.util.concurrent.CompletableFuture;

public class QwenExcutor implements Executor, ResultHandler {
    /**
     * OpenAi 接口
     */
    private final Configuration configuration;
    /**
     * 工厂事件
     */
    private final EventSource.Factory factory;
    /**
     * 统一接口
     */
    private IOpenAiApi openAiApi;

    private OkHttpClient okHttpClient;

    public QwenExcutor(Configuration configuration) {
        this.configuration = configuration;
        this.factory = configuration.createRequestFactory();
        this.openAiApi = configuration.getOpenAiApi();
        this.okHttpClient = configuration.getOkHttpClient();
    }

    @Override
    public EventSource completions(ChatCompletionCommonRequest chatCompletionRequest, EventSourceListener eventSourceListener) throws Exception {
        // 构建请求信息
        Request request = new Request.Builder()
                .url(configuration.getApiHost().concat(IOpenAiApi.Qwen_v1))
                .post(RequestBody.create(MediaType.parse(Configuration.JSON_CONTENT_TYPE), chatCompletionRequest.toString()))
                .build();

        // 返回事件结果
        return factory.newEventSource(request, eventSourceListener(eventSourceListener));
    }


    @Override
    public CompletableFuture<String> completions(ChatCompletionCommonRequest chatCompletionRequest) throws InterruptedException {
        throw new UnsupportedOperationException("暂未实现");
    }

    @Override
    public ChatCompletionSyncResponse completionsSync(ChatCompletionCommonRequest chatCompletionRequest) throws Exception {
        throw new UnsupportedOperationException("暂未实现");
    }

    @Override
    public ImageCompletionResponse genImages(ImageCompletionRequest request) throws Exception {
        throw new UnsupportedOperationException("暂未实现");
    }

    @Override
    public EventSourceListener eventSourceListener(EventSourceListener eventSourceListener) {
        return new EventSourceListener() {
            @Override
            public void onEvent(EventSource eventSource, @Nullable String id, @Nullable String type, String data) {
                if ("[DONE]".equals(data)) {
                    return;
                }
                ChatCompletionResponse response = null;
                try {
                    response = JSON.parseObject(data, ChatCompletionResponse.class);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                if (response.getChoices() != null && 1 == response.getChoices().size() && "stop".equals(response.getChoices().get(0).getFinishReason())) {
                    eventSourceListener.onEvent(eventSource, id, EventType.finish.getCode(), data);
                    return;
                }
                eventSourceListener.onEvent(eventSource, id, EventType.add.getCode(), data);
            }

            @Override
            public void onClosed(EventSource eventSource) {
                eventSourceListener.onClosed(eventSource);
            }

            @Override
            public void onFailure(EventSource eventSource, @Nullable Throwable t, @Nullable Response response) {
                eventSourceListener.onFailure(eventSource, t, response);
            }
        };
    }

}
